import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  TimePicker, 
  Space, 
  Tag, 
  message,
  Popconfirm,
  Row,
  Col,
  Statistic
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  CalendarOutlined,
  ClockCircleOutlined,
  UserOutlined,
  BookOutlined
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

export default function Schedule() {
  const [schedules, setSchedules] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingSchedule, setEditingSchedule] = useState(null);
  const [courses, setCourses] = useState([]);
  const [teachers, setTeachers] = useState([]);
  const [form] = Form.useForm();

  // 获取课程排班列表
  const fetchSchedules = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get('http://localhost:3001/api/schedules', {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      if (response.data.success) {
        setSchedules(response.data.data);
      }
    } catch (error) {
      console.error('获取课程排班失败:', error);
      message.error('获取课程排班失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取课程列表
  const fetchCourses = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get('http://localhost:3001/api/courses', {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      if (response.data.success) {
        setCourses(response.data.data);
      }
    } catch (error) {
      console.error('获取课程列表失败:', error);
    }
  };

  // 获取教师列表
  const fetchTeachers = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get('http://localhost:3001/api/teachers', {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      if (response.data.success) {
        setTeachers(response.data.data);
      }
    } catch (error) {
      console.error('获取教师列表失败:', error);
    }
  };

  useEffect(() => {
    fetchSchedules();
    fetchCourses();
    fetchTeachers();
  }, []);

  // 处理添加/编辑排班
  const handleSubmit = async (values) => {
    try {
      // 获取当前用户信息
      const currentUser = localStorage.getItem('currentUser');
      const userInfo = currentUser ? JSON.parse(currentUser) : {};
      
      // 获取课程和教师名称
      const selectedCourse = courses.find(c => c._id === values.courseId);
      const selectedTeacher = teachers.find(t => t._id === values.teacherId);
      
      const scheduleData = {
        ...values,
        courseName: selectedCourse ? selectedCourse.name : '',
        teacherName: selectedTeacher ? selectedTeacher.name : '',
        startTime: values.startTime.format('HH:mm'),
        endTime: values.endTime.format('HH:mm'),
        date: values.date.format('YYYY-MM-DD'),
        createdByUsername: userInfo.username || 'admin' // 添加创建者用户名
      };

      const token = localStorage.getItem('token');
      if (editingSchedule) {
        // 编辑
        await axios.put(`http://localhost:3001/api/schedules/${editingSchedule._id}`, scheduleData, {
          headers: {
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
          }
        });
        message.success('课程排班更新成功');
      } else {
        // 添加
        await axios.post('http://localhost:3001/api/schedules', scheduleData, {
          headers: {
            'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
          }
        });
        message.success('课程排班添加成功');
      }

      setModalVisible(false);
      setEditingSchedule(null);
      form.resetFields();
      fetchSchedules();
    } catch (error) {
      console.error('保存课程排班失败:', error);
      message.error('保存失败');
    }
  };

  // 删除排班
  const handleDelete = async (id) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`http://localhost:3001/api/schedules/${id}`, {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      message.success('删除成功');
      fetchSchedules();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 编辑排班
  const handleEdit = (record) => {
    setEditingSchedule(record);
    form.setFieldsValue({
      ...record,
      startTime: dayjs(record.startTime, 'HH:mm'),
      endTime: dayjs(record.endTime, 'HH:mm'),
      date: dayjs(record.date)
    });
    setModalVisible(true);
  };

  // 添加新排班
  const handleAdd = () => {
    setEditingSchedule(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 获取状态标签
  const getStatusTag = (status) => {
    const statusMap = {
      'scheduled': { color: 'blue', text: '已安排' },
      'ongoing': { color: 'green', text: '进行中' },
      'completed': { color: 'default', text: '已完成' },
      'cancelled': { color: 'red', text: '已取消' }
    };
    const statusInfo = statusMap[status] || { color: 'default', text: '未知' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '课程名称',
      dataIndex: 'courseName',
      key: 'courseName',
      render: (text, record) => {
        const course = courses.find(c => c._id === record.courseId);
        return course ? course.name : text;
      }
    },
    {
      title: '教师',
      dataIndex: 'teacherName',
      key: 'teacherName',
      render: (text, record) => {
        const teacher = teachers.find(t => t._id === record.teacherId);
        return teacher ? teacher.name : text;
      }
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      render: (text) => dayjs(text).format('YYYY-MM-DD')
    },
    {
      title: '时间',
      key: 'time',
      render: (_, record) => (
        <span>
          {record.startTime} - {record.endTime}
        </span>
      )
    },
    {
      title: '教室',
      dataIndex: 'classroom',
      key: 'classroom'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => getStatusTag(status)
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个排班吗？"
            onConfirm={() => handleDelete(record._id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总排班数"
              value={schedules.length}
              prefix={<CalendarOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日排班"
              value={schedules.filter(s => s.date === dayjs().format('YYYY-MM-DD')).length}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="进行中"
              value={schedules.filter(s => s.status === 'ongoing').length}
              prefix={<BookOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={schedules.filter(s => s.status === 'completed').length}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作按钮 */}
      <Card style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加排班
        </Button>
      </Card>

      {/* 排班表格 */}
      <Card title="课程排班管理">
        <Table
          columns={columns}
          dataSource={schedules}
          rowKey="_id"
          loading={loading}
          pagination={{
            total: schedules.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
        />
      </Card>

      {/* 添加/编辑模态框 */}
      <Modal
        title={editingSchedule ? '编辑课程排班' : '添加课程排班'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingSchedule(null);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="courseId"
                label="课程"
                rules={[{ required: true, message: '请选择课程' }]}
              >
                <Select placeholder="选择课程">
                  {courses.map(course => (
                    <Option key={course._id} value={course._id}>
                      {course.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="teacherId"
                label="教师"
                rules={[{ required: true, message: '请选择教师' }]}
              >
                <Select placeholder="选择教师">
                  {teachers.map(teacher => (
                    <Option key={teacher._id} value={teacher._id}>
                      {teacher.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="date"
                label="日期"
                rules={[{ required: true, message: '请选择日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="classroom"
                label="教室"
                rules={[{ required: true, message: '请输入教室' }]}
              >
                <Input placeholder="请输入教室" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="startTime"
                label="开始时间"
                rules={[{ required: true, message: '请选择开始时间' }]}
              >
                <TimePicker format="HH:mm" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="endTime"
                label="结束时间"
                rules={[{ required: true, message: '请选择结束时间' }]}
              >
                <TimePicker format="HH:mm" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="选择状态">
              <Option value="scheduled">已安排</Option>
              <Option value="ongoing">进行中</Option>
              <Option value="completed">已完成</Option>
              <Option value="cancelled">已取消</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="备注"
          >
            <TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingSchedule ? '更新' : '添加'}
              </Button>
              <Button onClick={() => {
                setModalVisible(false);
                setEditingSchedule(null);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
} 